# coding=utf-8
from PIL import Image
import math,os,sys,time,re,json 
class DigestionTime:    
    def __init__(self):
        self.start = time.time()
    def end(self):
        end = time.time()
        return end-self.start
class SplitGraph:
    def __init__(self,obj={}): 
        DTime=DigestionTime()
        self.Argv=obj
        _MinValue=int(obj.get('MinValue'))
        _SavePath=obj.get("save")
        self.SavePath=_SavePath
        imgFile=obj.get("img")
        if os.path.exists(_SavePath+'Drive.json'):
            pass
        elif os.path.exists(imgFile):
            img=None
            try:
                 img = self.openimage(imgFile)
            except IOError:
                img=None
                print("Error:1007")
            if img==None:
                return
            width,height = img.size[0], img.size[1]
            maxValue=width       
            if height>width:
                maxValue=height
            if _MinValue<maxValue:             
                mapParamet=self.getMapParamet(maxValue,_SavePath) 
                maxValue=mapParamet.value
                left=int((maxValue-width)/2)
                top=int((maxValue-height)/2)
                if mapParamet.zoom<10:
                    mapParamet.Img=img#imgself.paste(maxValue,left,top,img) 
                    self.start(mapParamet,left,top,width,height)         
                mapParamet.SaveDrive(DTime.end())
                if obj.get('get'):
                    print(DTime.end())
                    print(obj.get('get'))
            else:
                if img!=None and img.close:
                    img.close()       
        else:
            print('error')
        #new_img.save('newimg.png')
        #img = Image.open(imgFile)
    def openimage(self,imgFile):
        img = Image.open(imgFile) 
        return img
    def paste(self,value,left,top,img):
            Img = Image.new('RGBA', (value, value), (256,256,256,256))    
            Img.paste(img, (left, top))
            img.close()
            return Img
    def getMapParamet(self,mw,File):        
        for i in range(20):
            if math.pow(2, i)*256>=mw:  
                value=int(math.pow(2, i)*256) #mw+(256-mw%256) 
                return MapParamet(i,value,value,File)
        return MapParamet(0,256)
    def start(self,mapParamet,left=0,top=0,width=256,height=256):
        zoom=mapParamet.getDrive(width ,height,left, top) 
        for obj in zoom:
            if obj.z<10:                  
                z=obj.z   
                mapParamet.Resize(obj.width,obj.height)
                mb=0;
                for x in obj.xList:
                    for y in obj.yList: 
                        mb=mb+1
                        Y=y*(256)
                        X=x*(256)
                        item=GraphItem(X-obj.left,Y-obj.top,obj.width,obj.height)                               
                        item.Save(mapParamet.GetSaveFile(z,x,y),mapParamet.Img)            
                time.sleep(z)
class Graph:    
    def __init__(self, z,  value,xList,yList,width ,height,left=0, top=0):
        self.z=z
        self.value=value
        self.xList=xList
        self.yList=yList
        self.width=int(width)
        self.height=int(height)
        self.left=int(left)
        self.top=int(top)
class GraphItem:
    def __init__(self, left,top,width,height):
        self.left=left
        self.top=top
        self.width=width
        self.height=height
    def Save(self,_file,Img,Argv={}):
        if not os.path.exists(_file): 
            _width=min(self.width,self.left+256)
            _height=min(self.height,self.top+256)
            if self.top<_height and self.left<_width and _width>0 and _height>0:                
                left=self.left
                top=self.top
                if top<0:
                    top=0
                if left<0:
                    left=0
                region = (left,top,_width,_height)
                img = Img.crop(region) 
                cropImg = Image.new('RGBA', (256, 256), (0,0,0,0)) 
                if self.top<0:
                    top=self.top*-1
                else:
                    top=0
                if self.left<0:
                    left=self.left*-1
                else:
                    left=0
                cropImg.paste(img,(left,top))
                cropImg.save(_file)
                cropImg.close()
            elif Argv.get('blank')=='yes':
                cropImg = Image.new('RGBA', (256, 256), (256,256,256,256))
                cropImg.save(_file)
class MapParamet:
    def mkdir(self,path):
         if not os.path.isdir(path):
             os.mkdir(path)
    def Resize(self,width=256,height=256):
        if self.Img.width>width and self.Img.height>height:
            self.Img=self.Img.resize((width,height))
    def __init__(self, zoom,  value,maxvalue,File=''):
        self.zoom = zoom
        self.value = value
        self.maxvalue = maxvalue
        self.Img=None
        self.File=File
    def SetNewImage(self,img):
        self.Img.close()
        self.Img=img
    def SaveDrive(self,_time=0):
        obj={'zoom':self.zoom,'DigestionTime':_time,'Drive':self.Drive}  
        self.Img.close()                      
        f = open(self.File+'Drive.json','w')
        f.write(json.dumps(obj))
        f.close()
    def getDrive(self,width=256,height=256,left=0, top=0):
        zoom=range(self.zoom+1)
        zoom.reverse()
        Zm=[];
        Drive={}
        for z in zoom:            
            Vo=math.pow(2, self.zoom-z)            
            #v=int(math.pow(2, z)*256)
            v=self.value/ Vo
            v=int(v)
            if v%256>0:
                v=v+(256-v%256)
            Left=left/Vo
            Top=top/Vo
            Width=width/Vo
            Height=height/Vo
            value=range(v/256)
            Bottom=(Height+Top)            
            Right=(Width+Left)
            obj={'left':int((Left-(Left%256))/256),'bottom':int((Bottom+(256-Bottom%256))/256),'right':int((Right+(256-Right%256))/256),'top':int((Top-(Top%256))/256)}
            Drive['z-'+str(z)]=obj
            Zm.append(Graph(z,v,value,value,Width,Height,Left, Top))
        self.Drive=Drive
        return Zm
    def GetSaveFile(self, z,  x,  y):
        File= self.File+'{z}/'
        File=File.replace("{z}", str(z))
        self.mkdir(File)
        File=File+'{x}_{y}.png'
        return File.replace("{z}", str(z)).replace("{x}", str(x)).replace("{y}", str(y))

